<?php


namespace App\Http\Controllers\Front;


use App\Http\Controllers\Controller;
use App\Model\Advertisement;
use App\Model\Articles;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Swagger\Annotations as SWG;

class IndexController extends Controller
{

    /**
     * @SWG\Get(
     *     path="/front/index/slides",
     *     tags={"文章相关"},
     *     summary="首页轮播",
     *     description="首页轮播",
     *     produces={"application/json"},
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="images", type="string", description="图片"),
     *                  @SWG\Property(property="url", type="string", description="地址"),
     *              )
     *          )
     *      )
     * )
     */
    public function slides()
    {
        //下架广告
        DB::table('advertisement')->where('survival_begin', '>' , Carbon::now())->orWhere('survival_end', '<', Carbon::now())->update(['status'=>3]);
        //上架且在存活时间内
        $ad = Advertisement::where("type", 1)
            ->select("id", "images", "url")
            ->where("status", 2)
            ->where("survival_begin", "<", Carbon::now())
            ->where("survival_end", ">", Carbon::now())
            ->get();
        return $this->renderJson($ad);
    }

    /**
     * @SWG\Get(
     *     path="/front/index/follow/user",
     *     tags={"文章相关"},
     *     summary="首页关注用户",
     *     description="首页关注用户",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="account", type="string", description="名字"),
     *                  @SWG\Property(property="avatar", type="string", description="头像"),
     *              )
     *          )
     *      )
     * )
     */
    public function followUser()
    {
        $uids = $this->followId();
        //关注的用户信息
        $u = DB::table("media_user_info")->select('media_user_id as id','account','avatar')->
            whereIn("media_user_id", $uids)->
            get();
        return $this->renderJson($u);
    }

    /**
     * @SWG\Get(
     *     path="/front/index/follow/article",
     *     tags={"文章相关"},
     *     summary="首页关注用户",
     *     description="首页关注用户",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Parameter(name="author", in="query", type="integer", description="作者id"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="id"),
     *                  @SWG\Property(property="author_id", type="integer", description="作者id"),
     *                  @SWG\Property(property="title", type="string", description="文章标题"),
     *                  @SWG\Property(property="author_name", type="string", description="作者名字"),
     *                  @SWG\Property(property="auhtor_avatar", type="string", description="作者头像"),
     *                  @SWG\Property(property="pageviews", type="integer", description="浏览量"),
     *                  @SWG\Property(property="cover", type="string", description="封面"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="作者头像"),
     *              )
     *          )
     *      )
     * )
     */
    public function followArticle()
    {
        $uids = $this->followId();
        if (request()->has('author')){
            if (!in_array((int)request('author'), $uids->toArray())) {
                return $this->renderJson();
            }
            $uids = array(request('author'));
        }
//        $a = DB::table('articles as a')->
//        select('a.id', 'a.author as author_id','a.title' ,'u.account as author_name', 'u.avatar as author_avatar', 'a.created_at', 'a.pageviews', 'a.cover')
//            ->whereIn('author', $uids)
//            ->leftJoin("media_user_info as u", "u.media_user_id", "=", 'a.author')
//            ->where('a.status', 2)
//            ->orderByDesc('a.created_at')
//            ->paginate(request('limit', 15));
        $data = Articles::whereIn('author', $uids)->where('status', 2)->orderByDesc('created_at')->paginate(request('limit', 15));
        $list = $data->items();
        $res = [];
        foreach ($list as $item) {
            $tmp = [
                'id' => $item->id,
                'author_id' => $item->author,
                'title' => $item->title,
                'author_name' => $item->author_info?$item->author_info->account:'',
                'author_avatar' => $item->author_info?$item->author_info->avatar:'',
                'pageviews' => $item->pageviews,
                'cover' => $item->cover,
                'created_at' => $item->created_at->format('Y-m-d')
            ];
            $res[] = $tmp;
        }
        $data = $data->toArray();
        $data['data'] = $res;
        return $this->renderJson($data);
    }

    private function followId()
    {
        return DB::table("follow")->where("user_id", Auth::id())->where("status", 1)->pluck("media_user_id");
    }

    /**
     * @SWG\Get(
     *     path="/front/index/recommend",
     *     tags={"文章相关"},
     *     summary="首页推荐",
     *     description="首页推荐",
     *     produces={"application/json"},
     *     @SWG\Parameter(ref="#/parameters/auth"),
     *     @SWG\Response(
     *          response="200",
     *          description="调用成功",
     *          @SWG\Schema(
     *              type="array",
     *              @SWG\Items(
     *                  @SWG\Property(property="id", type="integer", description="文章或广告id"),
     *                  @SWG\Property(property="title", type="string", description="文章或广告标题"),
     *                  @SWG\Property(property="sub_title", type="string", description="文章短标题"),
     *                  @SWG\Property(property="cover", type="string", description="文章封面"),
     *                  @SWG\Property(property="sort_desc", type="string", description="文章简短简介"),
     *                  @SWG\Property(property="pageview", type="integer", description="文章浏览量"),
     *                  @SWG\Property(property="created_at", type="string", format="date", description="文章发布时间"),
     *                  @SWG\Property(property="is_ad", type="boolean", description="是否是广告"),
     *                  @SWG\Property(property="describe", type="string", description="广告简介"),
     *                  @SWG\Property(property="cover_path", type="string", description="广告图片"),
     *                  @SWG\Property(property="url", type="string", description="广告url"),
     *                  @SWG\Property(property="author", type="string", description="作者"),
     *              )
     *          )
     *      )
     * )
     */
    public function recommend(Articles $article)
    {
//        $articles = $article->where('status', 2)->where('article_category_id', '=', 36)->orderByDesc('created_at')->paginate(request('limit'));
//        if (empty($articles)) {
//            return $this->renderJson();
//        }
        $ad = Advertisement::select("id", 'name', "images", "url")
            ->where("status", 2)
            ->where("survival_begin", "<", Carbon::now())
            ->where("survival_end", ">", Carbon::now())
            ->where("type", 3)
            ->where("cate", 36)
            ->inRandomOrder()
            ->first();
        //$data = $articles->toArray();


        //没有登录就随机推荐
//        if (!Auth::check()) {
//            $items = DB::table('articles')->inRandomOrder()->take(10)->get();
//            $data = [];
//            foreach ($items as $item) {
//                $data[] = [
//                    'id' => $item->id,
//                    'title' => $item->title,
//                    'cover_path' => $item->cover_path,
//                    'sort_desc' => mb_substr(strip_tags(html_entity_decode($item->content)), 0, 50),
//                    'pageviews' => $item->pageviews,
//                    'created_at' => $item->created_at
//                ];
//            }
//            return $this->renderJson($data);
//        }
//        //用户浏览近10条记录文章id
//        $history = DB::table('view_article_log')->select('*', DB::raw('count(*) as count'))->where('u_id', Auth::id())->groupBy('a_id')->take(3)->get();
//
//        $p = new Participle(storage_path('dict.json'));
//        $dict = [];
//        $filter = ['，', ',', '。', '.', '‘', '’', "'", '“', '”', '"', '！', '!', '？', '?', '、', ''];
//        //分词
//        foreach ($history as $h){
//            foreach ($p->getWord($h->title) as $s){
//                $str = trim(array_first($s));
//                if (!in_array($str, $filter)) {
//                    $dict[] = $str;
//                }
//            }
//        }
//        //去重
//        $dict = array_unique($dict);
//        $where = implode('|', $dict);
//        $items = DB::table('articles')->where('title', 'REGEXP', $where)->take(10)->get();
//        $len = count($items);
//        if ($len < 10){
//            $rep = DB::table('articles')->inRandomOrder()->take(10 - $len)->get();
//            $items = $items->merge($rep);
//        }
        //$items = $article->where('status', 2)->where('id', '>=', DB::raw('((select max(id) from articles) - (select min(id) from articles)) *RAND() +(select min(id) from articles)'))->take(10)->get();
        $items = $article->where('status', 2)->where('created_at', '>', Carbon::now()->startOfQuarter()->toDateString())->inRandomOrder()->take(10)->get();
        $c = count($items);
        $r = mt_rand(0, $c);
        $data['data'] = [];
        foreach ($items as $k=>$a) {
            if ($k == $r && $ad != null){
                $data['data'][] = [
                    'id' => $ad->id,
                    'title' => $ad->name,
                    'author' => '汇营天下官方',
                    'describe' => $ad->describe,
                    'cover' => $ad->images,
                    'url' => $ad->url,
                    'created_at' => $ad->created_at,
                    'pageviews' => '',
                    'sub_title' => '',
                    'is_ad' => true,
                    'sort_desc' => ''
                ];
                continue;
            }
            $data['data'][] = [
                'id' => $a->id,
                'title' => $a->title,
                'sub_title' => $a->sub_title,
                'author' => $a->author_info?$a->author_info->account:'汇营天下官方',
                'cover' => $a->cover,
                'sort_desc' => mb_substr(strip_tags(html_entity_decode($a->content)), 0, 50),
                'pageviews' => $a->pageviews,
                'created_at' => $a->created_at->format('Y-m-d'),
                'is_ad' => false,
                'describe' => '',
                'url' => ''
            ];
        }
        return $this->renderJson($data);
    }
}